<template>
 <div>
    <van-nav-bar
      :title="$route.name"
      @click-left="$router.back()"
      left-text="返回"
      left-arrow
    />
    <!-- 购物车的视图分为有数据和无数据 -->
    <!-- 有数据 -->
    <div v-if="cartList.length > 0">
      <van-swipe-cell v-for="item in cartList" :key="item.id">
        <van-card
          :num="item.num"
          :price="item.price | toPrice"
          desc="描述信息"
          :title="item.goodsname"
          class="goods-card"
          :thumb="item.img"
        >
          <template #footer>
            <van-stepper
              v-model="item.num"
              theme="round"
              button-size="22"
              disable-input
            /> </template
        ></van-card>
        <template #right>
          <van-button
            @click="del(item.id)"
            square
            text="删除"
            type="danger"
            class="delete-button btnInfo"
          />
        </template>
      </van-swipe-cell>
    </div>
    <!-- 无数据状态 -->
    <div v-else>
      <van-empty description="购物车空空如也，快去买买买！！！" />
    </div>
 </div>
</template>

<script>
import { cartList,deleteCart } from '../request/api'
import {Toast} from 'vant'
import { log } from 'util';
export default {
    data(){
        return {
            cartList:[],
        };
    },
    //进入购物车之前进行登录判断
    beforeRouteEnter(to,from,next){
        if(sessionStorage.getItem("userinfo")){
            next();
        }else{
            next('/login');
        }
    },
    mounted(){
        //组件一加载就调用购物车列表
        cartList({
            uid:this.$store.getters.getUser.uid,
        }).then((res)=>{
            console.log(res,'购物车列表')
            if(res.code==200){
                this.cartList = res.list?res.list:[]
            }
        });
    },
    methods:{
        //封装一个删除事件
        del(id){
            deleteCart({id})
            .then((res)=>{
                if(res.code==200){
                    Toast.success(res.msg)
                    location.reload()
                }else{
                    Toast.fail(res.msg)
                }
            })
        }
    }
}
</script>

<style scoped>

</style>
